<template>
  <div class="container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="分类">
        <el-autocomplete
          v-model="searchKeyword"
          :fetch-suggestions="searchCategoryAsync"
          placeholder="请输入分类名称搜索"
          clearable
          @select="handleCategorySelect"
          @clear="clearCategorySearch"
          style="width: 300px"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
          <template #default="{ item }">
            <div class="search-result-item">
              <span>{{ item.name }}</span>
              <span v-if="item.parentName" class="parent-category">
                ({{ item.parentName }})
              </span>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>

      <el-form-item label="操作时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="success"
          icon="el-icon-download"
          @click="handleExport"
          :loading="exportLoading"
        >导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <!-- 数据表格 - 调整列宽和顺序 -->
    <el-table :data="logList" border style="width: 100%">
      <!-- 操作时间 -->
      <el-table-column
        prop="createTime"
        label="操作时间"
        width="160"
        align="center"
        :formatter="formatDate"
      />

      <!-- 父类名称 -->
      <el-table-column
        prop="parentName"
        label="父类"
        width="120"
        align="center"
      />

      <!-- 分类名称 -->
      <el-table-column
        prop="name"
        label="分类"
        width="300"
        align="center"
      />

      <!-- 操作类型 -->
      <el-table-column
        label="类型"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.operationType === 1 ? 'success' : 'danger'">
            {{ scope.row.operationType === 1 ? '入库' : '出库' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 库存信息 -->
      <el-table-column label="库存" align="center">
        <el-table-column
          prop="operationBeforeCount"
          label="操作前"
          width="100"
          align="center"
        />
        <el-table-column
          prop="operationNum"
          label="操作数量"
          width="100"
          align="center"
        />
        <el-table-column
          prop="operationAfterCount"
          label="操作后"
          width="100"
          align="center"
        />
        <el-table-column
          prop="surplusCount"
          label="当前库存"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <span style="font-weight:bold">{{ scope.row.surplusCount }}</span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import warehouseApi from "@/api/inventory/warehouse";
import Pagination from "@/components/Pagination";
import categoryApi from "@/api/inventory/category";
import { download } from "@/utils/request";


export default {
  name: "ComingOutLog",
  components: { Pagination },
  data() {
    return {
      exportLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        startTime: null,
        endTime: null
      },
      dateRange: [], // 日期范围
      total: 0, // 总记录数
      logList: [], // 表格数据
      categoryOptions: [], // 分类下拉选项
      searchKeyword: '', // 搜索关键词
      searchLoading: false, // 搜索加载状态
    };
  },
  created() {
    this.getList();
    this.getCategoryOptions();
  },
  methods: {
    handleExport() {
      this.exportLoading = true;

      // 准备导出参数
      const exportParams = {
        categoryId: this.queryParams.categoryId,
        startTime: this.dateRange && this.dateRange[0],
        endTime: this.dateRange && this.dateRange[1]
      };

      // 调用现有的下载方法
      download(
        "/api/exportComingOutLog", // 导出API路径
        exportParams,                        // 查询参数
        "出入库记录.xlsx",                  // 文件名
        { method: "post" }                   // 配置项
      )
        .finally(() => {
          this.exportLoading = false;
        });
    },
    /** 查询出入库记录 */
    getList() {
      const params = { ...this.queryParams };
      // 处理日期范围参数
      if (this.dateRange && this.dateRange.length === 2) {
        params.startTime = this.dateRange[0];
        params.endTime = this.dateRange[1];
      } else {
        params.startTime = null;
        params.endTime = null;
      }

      warehouseApi.comingOutLog(params).then(response => {
        // 确保正确设置数据 - 关键修复：使用 response.data
        console.log('API响应:', response);
        const resData = response.data || {};
        this.logList = resData.records || [];
        this.total = Number(resData.total) || 0; // 确保转换为数字

        console.log('获取的出入库记录:', {
          logList: this.logList,
          total: this.total
        }); // 调试日志
      }).catch(error => {
        console.error("获取出入库记录失败:", error);
        this.logList = [];
        this.total = 0;
      });
    },

    /** 获取分类下拉选项 */
    async getCategoryOptions() {
      try {
        const res = await categoryApi.getCategoryTree();
        // 确保正确处理API响应
        const resData = res.data || [];
        console.log('获取的分类树:', resData); // 调试日志

        // 递归函数：将树形结构扁平化
        const flattenCategories = (categories) => {
          let result = [];
          categories.forEach(category => {
            result.push({
              value: category.id,
              label: category.name
            });
            if (category.children && category.children.length > 0) {
              result = result.concat(flattenCategories(category.children));
            }
          });
          return result;
        };

        // 转换为下拉选项格式
        this.categoryOptions = flattenCategories(resData);
      } catch (error) {
        console.error("获取分类选项失败:", error);
        this.categoryOptions = [];
      }
    },

    /** 分类搜索建议 */
    searchCategoryAsync(queryString, callback) {
      if (!queryString) {
        callback([]);
        return;
      }

      this.searchLoading = true;

      // 调用分类搜索API
      categoryApi.searchCategories({ keyword: queryString })
        .then(response => {
          const results = response.data || [];
          // 格式化结果用于自动完成组件
          const suggestions = results.map(item => ({
            ...item,
            value: item.name // el-autocomplete需要的value字段
          }));
          callback(suggestions);
        })
        .catch(error => {
          console.error('搜索分类失败:', error);
          callback([]);
        })
        .finally(() => {
          this.searchLoading = false;
        });
    },

    /** 处理分类选择 */
    handleCategorySelect(item) {
      this.queryParams.categoryId = item.id;
      this.searchKeyword = item.name;
      this.handleQuery();
    },

    /** 清除分类搜索 */
    clearCategorySearch() {
      this.queryParams.categoryId = null;
      this.searchKeyword = '';
      this.handleQuery();
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.dateRange = [];
      this.searchKeyword = '';
      this.queryParams.categoryId = null;
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    /** 格式化日期 */
    formatDate(row, column, cellValue) {
      if (!cellValue) return '-';

      try {
        // 处理不同格式的日期值
        const date = new Date(cellValue);

        // 检查是否是有效日期
        if (isNaN(date.getTime())) {
          // 尝试解析字符串格式
          const parts = cellValue.split(/[-T:.]/);
          if (parts.length >= 3) {
            return `${parts[0]}-${parts[1]}-${parts[2]}`;
          }
          return cellValue; // 无法解析则返回原始值
        }

        // 格式化日期为 YYYY-MM-DD HH:mm:ss
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } catch (e) {
        console.error('日期格式化错误:', e);
        return cellValue; // 出错时返回原始值
      }
    },
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.parent-category {
  color: #909399;
  font-size: 12px;
}
</style>
